<!--校区开设-->
<template>
  <div class="campus_management_container">
    <div class="search_box">
      <!-- <el-button type="primary" class="fl" @click="showPopup">新增</el-button> -->
      <div v-if="powerList.add.show == 1" class="btn btn_add" @click="showPopup('ruleForm')">
        <i class="el-icon-plus"></i>
        <span class="btn_txt">添加</span>
      </div>
      <div class="fr" >
        <el-form :model="searchForm" :inline="true" class="searchForm">
          <el-form-item size="small" style="width:180px;">
            <el-select v-model="searchForm.schoolId" @change="changeSchool" clearable placeholder="校区">
              <el-option v-for="(item,key) in schoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item size="small" style="width:150px;">
            <el-select v-model="searchForm.courseId" clearable placeholder="大类">
              <el-option v-for="(item,key) in courseList" :key="key" :label="item.courseName" :value="item.courseId">
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item size="small" style="width: 220px; margin-right: 0;">
            <el-input placeholder="输入课程产品名称/编号" size="small" v-model="searchForm.searchValues" @keyup.enter.native="searchData(searchValue)">
              <div slot="append" class="btn_search" @click="searchData(searchValue)">查询</div>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="clear"></div>
    </div>
    
    <div class="table_box">
      <adminTable :tableHead="tableHead" :tableData="tableData"></adminTable>
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.curPage"
        :page-sizes="[10, 20, 50]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.totalRows">
      </el-pagination>
    </div>

    <transition name="el-fade-in-linear">
      <div class="popup-container" v-show="popupState.showStatus">
        <div class="popup">
          <i class="el-icon-error icon_close" @click="popupState.showStatus = false;"></i>
          <div class="title">{{popupState.popupName}}</div>

          <div class="content table_content">
            <el-form :model="formData" :disabled="checkStatus" ref="ruleForm" :rules="rules" label-position="left"  style=""
               class="form" :inline="true" >
              <div style="overflow:hidden">
                
                <el-form-item label="大类 : " prop="courseId" size="small"  >
                  <el-select v-model="formData.courseId"  placeholder="大类" @change="changeCourse">
                    <el-option v-for="(item,key) in courseList" :key="key" :label="item.courseName" :value="item.courseId">
                    </el-option>
                  </el-select>
                </el-form-item>
                
                <el-form-item label="课程产品名称 : "  prop="productId" size="small" >
                  <el-select  v-model="formData.productId" @change="changeProduct" placeholder="课程产品名称">
                    <el-option v-for="(item,key) in productList" :key="key" :label="item.productName" :value="item.productId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="校区 : " prop="schoolId" size="small" >
                  <el-select  multiple collapse-tags style="width: 200px;" :disabled="this.popupState.popupName == '编辑校区课程产品'" v-model="formData.schoolId"  placeholder="选择校区">
                    <el-option v-for="(item,key) in powerSchoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
                    </el-option>
                  </el-select>
                </el-form-item>


                <div class="clear"></div>

                <!-- v-if="detailTableData.length != 0" -->
                <div class="detail_table" >
                  <adminTable :tableHead="detailTableHead" :tableData="detailTableData"></adminTable>
                  <adminTable :tableHead="detailTableHead2" :tableData="detailTableData"></adminTable>
                </div>

                <div class="content_detail_box">
                  <h4 style="font-size: 12px; margin-bottom: 10px;">
                    <span>内容详情 : </span>
                    <i @click="showDetailBox=false" v-if="showDetailBox" class="icon_open el-icon-arrow-up"></i>
                    <i @click="showDetailBox=true" v-else class="icon_open el-icon-arrow-down"></i>
                  </h4>

                  <div class="content_detail" v-if="showDetailBox">
                    <div class="desc_img">
                      <span>简介图片：</span>
                      <!--  -->
                      <uploadAliyun
                        :actionType="'CreateUploadImage'"
                        :imgUrl="formData.bmSchoolOpenExit.briefPictureUrl"
                        @uploadSuccess="(data) => uploadSuccess(data, this.formData.bmSchoolOpenExit, 'briefPicture')"
                        :messageTxt="'imageUrl'">
                      </uploadAliyun>
                    </div>

                    <div class="catalog_box">
                      <span>目录：</span>
                      <ul class="catalog_list" style="margin-left: 15px;">
                        <li class="catalog_item" v-for="(item, index) in formData.bmSchoolOpenExit.bmSchoolOpenExitContentList" :key="index">
                          <el-form-item label="章节名称 : "  prop="" size="mini" class="fl">
                            <el-input style="width: 180px;"  v-model="item.chapterName" autocomplete="off" placeholder=""></el-input>
                          </el-form-item>
                          <el-form-item label="时长: "  prop="" size="mini" class="fl">
                            <el-input style="width: 50px;"  v-model="item.durationTime" autocomplete="off" placeholder=""></el-input>
                            <span style="font-size: 12px">分钟</span>
                          </el-form-item>
                          <uploadAliyun
                            class="fl"
                            style="margin-right: 20px"
                            :actionType="'CreateUploadVideo'"
                            @uploadSuccess="(data) => uploadSuccess(data, item,  '上传音频')"
                            :messageTxt="item.voiceName || '上传本章视频'">
                          </uploadAliyun>
                          <el-form-item label="是否开放试听: "  prop="" size="mini" class="fl">
                            <el-radio v-model="item.isAudition" label="1">是</el-radio>
                            <el-radio v-model="item.isAudition" label="0">否</el-radio>
                          </el-form-item>

                          <i v-if="!checkStatus" @click="deleteCatalog(index)"  class=" el-icon-remove-outline"></i>
                          <i v-if="!checkStatus" @click="addCatalog(index)"  class=" el-icon-circle-plus-outline"></i>
                          <div class="clear"></div>
                        </li>
                      </ul>
                    </div>

                    <div class="desc_img">
                      <span>描述海报： </span>
                      <!-- :imgUrl="item.descriptionPoster" -->
                      <uploadAliyun
                        :actionType="'CreateUploadImage'"
                        :imgUrl="formData.bmSchoolOpenExit.descriptionPosterUrl"
                        @uploadSuccess="(data) => uploadSuccess(data, this.formData.bmSchoolOpenExit, 'descriptionPoster')"
                        :messageTxt="'imageUrl'">
                      </uploadAliyun>
                    </div>
                  </div>

                </div>

                

                <div class="discount_box">
                  <h4 style="font-size: 12px; margin-bottom: 10px;">优惠选择 : </h4>
                  <div class="discount_item" 
                    v-for="(item, index) in formData.bmSchoolOpenList" 
                    :key="index"
                  >
                    <!-- <span class="fl discount_title">优惠{{index+1}} : </span> -->
                    <el-form-item label="优惠类型" style="line-height: 30px;" size="mini" class="fl">
                      <el-select v-model="item.discountType" clearable style="width: 100px" >
                        <el-option v-for="(item, index) in discountSelectList" :key="index" :label="item.dicLabel" :value="item.dicCode"></el-option>
                      </el-select>
                    </el-form-item>

                    <el-form-item label="优惠生效期" style="line-height: 30px;" prop="discountPrice" size="mini" class="fl">
                      <el-date-picker
                        style="width: 213px;" 
                        v-model="item.validityTime"
                        type="daterange"
                        :default-time="['00:00:00', '23:59:59']"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                      </el-date-picker>
                    </el-form-item>
                    
                    <div class="fl preferential_amount" style="width: 28%">
                      <el-form-item label="优惠金额" style="line-height: 30px;" prop="discountPrice" size="mini" class="fl">
                        <el-input  placeholder="元或百分比" style="width: 100%; " v-model="item.discountPrice" class="input-with-select fl">
                          <el-select @change="(e) => changeType(e, index)" v-model="item.discountMethod" style="width: 55px" slot="append" placeholder=" ">
                            <el-option label="%" value="1"></el-option>
                            <el-option label="元" value="2"></el-option>
                          </el-select>
                        </el-input>
                      </el-form-item>
                    </div>
                    <div class="clear"></div>

                    <el-form-item label="优惠描述" style="line-height: 30px;" prop="remarkDiscount" size="mini" class="fl">
                      <el-input style="width: 398px;"  v-model="item.remarkDiscount" autocomplete="off" placeholder=""></el-input>
                    </el-form-item>

                    <i v-if="!checkStatus" @click="deleteDiscount(index)"  class="icon el-icon-remove-outline"></i>
                    <i v-if="!checkStatus" @click="addDiscount(index)"  class="icon el-icon-circle-plus-outline"></i>

                    <div class="clear"></div>
                  </div>
                  
                </div>

                <div class="conversion_rate_box">
                  <h4 style="font-size: 12px; margin-bottom: 10px;">转换率设置 : </h4>
                  <el-form-item label="有效单 > 试听(%) : " style="width: 23%" prop="" size="mini" class="fl">
                    <el-input style="width: 80px;"  v-model="formData.auditionRate" autocomplete="off" placeholder=""></el-input>
                  </el-form-item>
                  <el-form-item label="试听 >  定金(%): " style="width: 22%" prop="" size="mini" class="fl">
                    <el-input style="width: 80px;"  v-model="formData.earnestRate" autocomplete="off" placeholder=""></el-input>
                  </el-form-item>
                  <el-form-item label="定金 > 签单(%) : " style="width: 22%" prop="" size="mini" class="fl">
                    <el-input style="width: 80px;"  v-model="formData.signRate" autocomplete="off" placeholder=""></el-input>
                  </el-form-item>
                </div>

                


                <!-- <el-form-item label="联系人 : " prop="linkPerson" size="small" class="fl no_margin_right">
                  <el-input  v-model="formData.linkPerson" autocomplete="off" placeholder="输入联系人"></el-input>
                </el-form-item> -->

                

                

                

              </div>

            </el-form>

            <div class="btn_box" v-if="!checkStatus">
              <div class="btn btn_add" v-if="popupState.popupName == '添加校区课程产品'" @click="submitAdd('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>

              <div class="btn btn_add" v-if="popupState.popupName == '编辑校区课程产品'" @click="submitEdit('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>
            </div>

          </div>
        </div>
      </div>
    </transition>
  </div>
</template>


<style>
.catalog_item > i {
  color: #87AEFF;
  cursor: pointer;
  margin-left: 10px;
}
.catalog_box .el-radio{
  margin-right: 10px;
}
.catalog_box .el-radio__label {
  padding-left: 2px;
}
.catalog_item {
  display: flex;
  align-items: center;
  position: relative;
}
.catalog_box .el-form-item--mini.el-form-item, .catalog_box .el-form-item--small.el-form-item{
  width: auto !important;
  margin-right: 2% !important;
  margin-bottom: 0 !important;
}
.campus_management_container .discount_box .el-form-item__label{
  float: left !important;
}
.campus_management_container .discount_box .el-input--mini .el-input__icon {
  height: 28px !important;
}
.preferential_amount .el-form-item__content{
  width: 70% !important;
}
.preferential_amount .el-input__inner{
  padding-right: 0 !important;
}
.campus_management_container .popup .el-form-item--small.el-form-item {
  width: auto !important;
  margin-right: 1.5% !important;
}

.campus_management_container .popup .el-form-item--small.el-form-item {
  margin-bottom: 20px;
}

.campus_management_container .popup .el-form-item__label {
  font-size: 12px;
  /* line-height: 50px; */
}

.discount_title {
  margin: 0 10px;
  font-weight: 600;
  color: #070707;
}
.discount_item{
  padding: 5px 10px 4px 10px;
  position: relative;
}
.discount_item .el-form-item--mini.el-form-item{ 
  width: auto !important;
  margin-right: 1.5% !important;
  margin-bottom: 0 !important;
}
.discount_item .el-form-item__content, 
.discount_item .el-form-item__label {
  /* line-height: 50px; */
}

.discount_item .el-icon-remove-outline {
  right: 4px;
  top: 7px;
}
.discount_item .el-icon-circle-plus-outline {
  right: 4px;
  bottom: 7px;
}
</style>
<style scoped>
.content_detail > div{
  margin-bottom: 10px;
}
.desc_img {
  display: flex;
  align-items: center;
}
.icon_open{
  cursor: pointer;
}
.icon {
  color: #87AEFF;
  cursor: pointer;
  margin-left: 10px;
  position: absolute;
}
.discount_box, .content_detail_box {
  margin-top: 20px;
}
.discount_item {
  /* height: 50px; */
  background: #F0F2F5;
  line-height: 50px;
  margin-bottom: 20px;
}

.btn_box {
  margin-top: 20px;
}

</style>

<script>
import adminTable from '@/components/assembly/adminTable'
import uploadAliyun from '@/components/assembly/uploadAliyun'
import {
  createNamespacedHelpers
} from "vuex";
let {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("openCampus");
export default {
  name: 'openCampus',
  data() {
    return {
      powerList: {
        add: {
          show: 0,
          menuId: '',
        }
      },

      productId: '',
      jwtAuth: {},
      isLogin: false,
      checkStatus: false,
      showDetailBox: false,
      popupState: {
        showStatus: false,
        popupName: '添加校区课程产品',
      },
      page: {
        curPage: 1,
        pageSize: 10,
        totalRows: 0,
      },
      searchForm: {
        schoolId: '',
        entryType: '',
        positionType: '',
        searchValues: '',
        schoolIdArr: []
      },
      productPrice: '',
      formData: {
        schoolId: [],
        auditionRate: '',
        earnestRate: '',
        signRate: '',
        bmSchoolOpenExit: {
          briefPicture: '',
          descriptionPoster: '',
          bmSchoolOpenExitContentList: [
            {
              isAudition: '0',
              audioOrVideoFile: '',
              durationTime: '',
              fileType: 'video'
            }
          ],
        },
        bmSchoolOpenList: [
          { 
            discountType: '',
            remarkDiscount: '',
            discountPrice: '',
            validityTime: [],
            discountMethod: '',
            productId: '',
            subjectDiscount: '',
          },
        ]
      },
      searchValue: '',

      tableHead: {
        // border: true,
        // order: true,
        operation_width: '180px',
        setFunction: [
          {
            showState: "0",
            hideKey: "showDetail",
            fun: this.tableDetail,
            name: "详情"
          },
          {
            showState: "0",
            hideKey: "showUpdate",
            fun: this.tableEdit,
            name: "编辑"
          },
          {
            showState: "0",
            hideKey: "showDelete",
            fun: this.tableDelete,
            name: "删除"
          },
        ],
        data: [
          {
            name: '校区',
            key: 'schoolName',
            align: 'center',
          },
          {
            name: '课程产品名称',
            key: 'productName',
            align: 'center',
            // width: '70',
          },
          {
            name: "课程产品编号",
            key: "productCode",
            align: "center",
            width: '70',
          },
          {
            name: "大类",
            key: "courseName",
            align: "center",
            width: '',
          },
          {
            name: "总课时数",
            key: "totalHour",
            align: "center",
            width: '50',
          },
          {
            name: "周数",
            key: "weekMun",
            align: "center",
            width: '50',
          },
          {
            name: "课程指导价(元)",
            key: "productPrice",
            align: "center",
            width: '66',
          },
          {
            name: "餐费(元)",
            key: "mealsPrice",
            align: "center",
            width: '66px',
          },
          {
            name: "杂费(元)",
            key: "incidentalPrice",
            align: "center",
            width: '66px',
          },
          {
            name: "标准总价(元)",
            key: "totalPrices",
            align: "center",
          },
          // {
          //   name: "时效优惠",
          //   key: "discount",
          //   align: "center",
          //   // width: '50px'
          // },
          // {
          //   name: "当前售价(元)",
          //   key: "totalPrice",
          //   align: "center",
          // },
        ]
      },
      tableData: [],

      detailTableHead: {
        data: [
          {
            name: '课程产品名称',
            key: 'productName',
            align: 'center',
            width: '',
          },
          {
            name: "课程产品编号",
            key: "productCode",
            align: "center",
            width: '95',
          },
          {
            name: "最低开班人数",
            key: "courseName",
            align: "center",
            width: '95',
          },
          {
            name: "满班人数",
            key: "maxPerson",
            align: "center",
            width: '75',
          },
          
          {
            name: "课程指导价(元)",
            key: "productPrice",
            align: "center",
            width: '105',
          },
          {
            name: "餐费(元)",
            key: "mealsPrice",
            align: "center",
            width: '65',
          },
          {
            name: "杂费(元)",
            key: "incidentalPrice",
            align: "center",
            width: '65',
          },
          {
            name: "其它费用(元)",
            key: "otherPrice",
            align: "center",
            width: '100',
          },
          {
            name: "标准总价(元)",
            key: "totalPrices",
            align: "center",
            width: '100',
          },
        ]
      },
      detailTableHead2: {
        data: [
          {
            name: "周数(周)",
            key: "weekMun",
            align: "center",
            width: '',
          },
          {
            name: "总课时",
            key: "totalHour",
            align: "center",
            width: '',
          },
          {
            name: '科目选择',
            key: 'subjectName',
            align: 'center',
          },
          {
            name: "课时/周",
            key: "subjectHour",
            align: "center"
          },
          {
            name: "使用信息",
            key: "productRemark",
            align: "center"
          },
          {
            name: "附件信息",
            key: "fileName",
            align: "center"
          },
          
        ]
      },
      detailTableData: [],

      courseList: [],
      productList: [],
      schoolList: [],
      powerSchoolList: [],
      discountSelectList: [],

      discountIdList: [],       // 删除的 优惠列表

      rules: {
        accountName: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
        ],
        employeesName: [
          { required: true, message: '请输入产品姓名', trigger: 'blur' },
        ],
        entryType: [
          { required: true, message: '请选择入职类型', trigger: 'change' },
        ],
        entryTime: [
          { required: true, message: '请选择入职时间', trigger: 'change' },
        ],
        accountPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        subjectDiscount: [
          { required: true, message: '顶顶顶', trigger: 'blur' },
          // { min: 1, max: 2, message: '优惠在1-99之间', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {pattern: /^1[34578]\d{9}$/, message: '手机号格式错误'}
        ],
      },


    }
  },
  created() {
    this.jwtAuth = JSON.parse(sessionStorage.getItem('jwtAuth'));
    this.initSelect();
    this.queryAllSchool();

    // this.initDiscountSelect();    // 获取优惠类型 字典
  },
  // watch: {
  //   mapPowerList: {
  //     handler(newName, oldName) {
  //     },
  //     immediate: true,
  //     deep: true
  //   }
  // },
  
  methods: {
    ...mapMutations([
      // "updateInfo",
    ]),
    ...mapActions([
      "formGet",
      "post"
    ]),
    uploadSuccess(data, item, type) {
      console.log(data)
      console.log(item)

      switch (type) {
        
        case '上传音频':
          item.voiceName = data.fileName;
          item.audioOrVideoFile = data.VideoId;
          break;
        case 'briefPicture':
          item.briefPicture = data.ImageId
          this.getImgUrlByAliId(data, item, 'briefPictureUrl')
          break;
        case 'descriptionPoster':
          item.descriptionPoster = data.ImageId
          this.getImgUrlByAliId(data, item, 'descriptionPosterUrl')
          break;
      
        default:
          break;
      }

      this.$forceUpdate();

    },

    getImgUrlByAliId(data, item, type) {
      this.formGet({
        API: 'getImageInfoData',
        data: {
          imageId: data.ImageId,
        }
      }).then(res => {
        if(res.imageInfo) {
          let url = res.imageInfo.url;
          item[type] = url;
          this.$forceUpdate();
        }
      });
      
    },

    initData(searchForm) {
      // console.log(searchValue)
      let searchValue = searchForm || this.searchForm || '';
      let data = {}
      // let schoolId = [];
      // this.schoolList.forEach(item => {
      //   schoolId.push(item.schoolId)
      // })
      // let data = searchValue;
      Object.assign(data, searchValue);
      this.changeSchool(this.searchForm.schoolId)
      data.curPage = this.page.curPage;
      data.pageSize = this.page.pageSize;
      data.schoolId = this.searchForm.schoolIdArr;
      data.accountId = this.jwtAuth.accountId;
      data.menuId = this.$route.name;
      // console.log(searchValue.schoolId.split(','))
      //  || this.jwtAuth.schoolId
      data.isSchoolOpen = '';
      this.post({
        API: 'selectBmSchoolOpenPageList',
        data: data
      }).then(res => {
        this.tableData = res.data;
        
        res.buttons.menuList[0].children.forEach(item => {
          if(item.label == '添加') {
            this.powerList.add.show = 1
            this.powerList.add.menuId = item.menuId
          }
          // console.log(this.powerList)
        })
        
        res.data.forEach(item => {
          if(item.buttonMap) {
            let menuList = item.buttonMap.menuList[0].children
            menuList.forEach((menuItem, menuIndex) => {
              if(menuItem.menuId == '131111') {     // 详情
                if(menuItem.isDisplay == 1) {
                  item.showDetail = 1
                }else{
                  item.showDetail = 0
                }
              }
              if(menuItem.menuId == '131112') {     // 编辑
                if(menuItem.isDisplay == 1) {
                  item.showUpdate = 1
                }else{
                  item.showUpdate = 0
                }
              }
              if(menuItem.menuId == '131113') {     // 删除
                if(menuItem.isDisplay == 1) {
                  item.showDelete = 1
                }else{
                  item.showDelete = 0
                }
              } 
            })
          }
        })
 

        this.tableData.forEach(item => {
          let totalPrice;
          let arr = [];
          // console.log('bbbb')
          if(item.bmSchoolOpenList) {
            item.bmSchoolOpenList.forEach(childItem => {
              arr.push(childItem.remarkDiscount)
            })
            item.discount = arr.join('');

            let childItem = item.bmSchoolOpenList;
            for(let i=0; i<childItem.length; i++) {
              if(childItem[i].remarkDiscount.indexOf('span') >= 0) {
                item.totalPrice = childItem[i].totalPrice
                break;
              }else{
                item.totalPrice = item.totalPrices
              }
            }
          }
          
          
          // console.log('cccc')

          
        })

        this.page = res.page;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    

    initSelect() {
      this.post({
        API: 'queryAllCourseType',
        data: {}
      }).then(res => {
        this.courseList = res;
      }).catch(err => {
        this.$message.error(err);
      });
    },

    queryAllSchool(btnId) {
      let accountId
      this.jwtAuth.schoolId == '' ? accountId = '' : accountId = this.jwtAuth.accountId
      
      this.post({
        API: 'queryAllSchool',
        data: {
          accountId: accountId,
          menuId: btnId || this.$route.name,
          schoolIds: this.jwtAuth.schoolId.split(','),
        }
      }).then(res => {
        if(btnId) {
          this.powerSchoolList = res
          // this.selectClassSearch.schoolId = this.powerSchoolList[0].schoolId
        }else{
          this.schoolList = res
          this.initData();
        }
      }).catch(err => {
        this.$message.error(err)
      })
    },

    // 新增提交
    submitAdd(formName) {
      let data = this.formData;
      let numberReg = new RegExp(/^\d+(\.\d+)?$/);
      console.log(this.formData)
      let discountList = data.bmSchoolOpenList
      // discountMethod
      for(let i=0; i<discountList.length; i++) {
        if(discountList[i].discountType !== '') {     // 选中优惠类型
        
          if(discountList[i].remarkDiscount == '') {
            this.$message.error('请输入优惠描述')
            return false;
          }

          if(discountList[i].discountPrice == '') {
            this.$message.error('请输入优惠金额 或 优惠百分比')
            return false;
          }else if (!numberReg.test(discountList[i].discountPrice)) {
            this.$message.error('优惠金额只能是数字');
            return false;
          }
          if(discountList[i].discountMethod == '') {
            this.$message.error('请选择优惠单位: % 或 元')
            return false;
          }
        }

        if(discountList[i].discountPrice !== '') {     // 填了优惠价格
          if(discountList[i].discountType == '') {
            this.$message.error('请选择优惠类型')
            return false;
          }
          if(discountList[i].remarkDiscount == '') {
            this.$message.error('请输入优惠描述')
            return false;
          }

          if(discountList[i].discountMethod == '') {
            this.$message.error('请选择优惠单位: % 或 元')
            return false;
          }
        }

        if(discountList[i].discountMethod == 1) {
          if(discountList[i].discountPrice > 100) {
            this.$message.error('百分比不可大于 100');
            return false;
          }
        }else{
          if(discountList[i].discountPrice < 0) {  // 且不可大于 课程总价
            this.$message.error('优惠金额不可为负数');
            return false;
          }
        }


        /**
        * 时效优惠 时间不可为空
        */

       if(discountList[i].discountType == 1) {
         if(discountList[i].validityTime.length == 0) {
           this.$message.error('时效优惠时间不可为空');
           return false;
         }
       }
      }

      
      
      
      data.bmSchoolOpenList.forEach((item, index) => {

        item.productId = this.formData.productId;
        item.schoolId = data.schoolId.join(',');
        
        item.validityStartTime = item.validityTime[0]
        item.validityEndTime = item.validityTime[1]

        item.auditionRate = data.auditionRate
        item.earnestRate = data.earnestRate
        item.signRate = data.signRate


        if(item.discountMethod == 1) {    // %
          item.totalPrice = Number(this.productPrice) * Number(item.discountPrice / 100)
          
        }else{
          item.totalPrice = Number(this.productPrice) - Number(item.discountPrice)
        }

        item.totalPrice = (item.totalPrice + 
                          this.mealsPrice + 
                          this.incidentalPrice +
                          this.otherPrice).toFixed(0).toString();

      })

      data.bmSchoolOpenExit.bmSchoolOpenExitContentList.forEach((item, index) => {
        item.sort = index;
      });
      data.bmSchoolOpenExit.productId = this.formData.productId

      console.log(data);
      // return false;

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.post({
            API: 'insert',
            data: data
          }).then(res => {
            console.log(res)
            if(res == 1) {
              this.$message.success('新建成功')
              this.initData();
              this.popupState.showStatus = false;
            }
          }).catch(err => {
            this.$message.error(err);
          })
        } else {
          // console.log('error submit!!');
          return false;
        }
      });

      
    },

    // 编辑提交
    submitEdit(rowData) {
      let data = {};
      data = this.formData;
      let numberReg = new RegExp(/^\d+(\.\d+)?$/);
      let discountList = data.bmSchoolOpenList
      console.log(discountList)
      for(let i=0; i<discountList.length; i++) {
        if(discountList[i].discountType !== '') {     // 选中优惠类型
        
          if(discountList[i].remarkDiscount == '') {
            this.$message.error('请输入优惠描述')
            return false;
          }

          if(discountList[i].discountPrice == '') {
            this.$message.error('请输入优惠金额 或 优惠百分比')
            return false;
          }else if (!numberReg.test(discountList[i].discountPrice)) {
            this.$message.error('优惠金额只能是数字');
            return false;
          }
          if(discountList[i].discountMethod == '') {
            this.$message.error('请选择优惠单位: % 或 元')
            return false;
          }
        }

        if(discountList[i].discountPrice !== '') {     // 填了优惠价格
          if(discountList[i].discountType == '') {
            this.$message.error('请选择优惠类型')
            return false;
          }
          if(discountList[i].remarkDiscount == '') {
            this.$message.error('请输入优惠描述')
            return false;
          }

          if(discountList[i].discountMethod == '') {
            this.$message.error('请选择优惠单位: % 或 元')
            return false;
          }
        }

        if(discountList[i].discountMethod == 1) {
          if(discountList[i].discountPrice > 100) {
            this.$message.error('百分比不可大于 100');
            return false;
          }
        }else{
          if(discountList[i].discountPrice < 0) {  // 且不可大于 课程总价
            this.$message.error('优惠金额不可为负数');
            return false;
          }
        }

        /**
        * 时效优惠 时间不可为空
        */

       if(discountList[i].discountType == 1) {
         if(discountList[i].validityTime.length == 0) {
           this.$message.error('时效优惠时间不可为空');
           return false;
         }
       }
      }

      data.bmSchoolOpenList.forEach((item, index) => {

        item.productId = this.formData.productId
        item.schoolId = data.schoolId.join(',')

        item.auditionRate = data.auditionRate
        item.earnestRate = data.earnestRate
        item.signRate = data.signRate

        if(item.discountMethod == 1) {    // %
          item.totalPrice = Number(this.productPrice) * Number(item.discountPrice / 100)
        }else{
          item.totalPrice = Number(this.productPrice) - Number(item.discountPrice)
        }

        item.totalPrice = (item.totalPrice + 
                          this.mealsPrice + 
                          this.incidentalPrice +
                          this.otherPrice).toFixed(0).toString();

        console.log(item.validityTime)
        if(item.validityTime) {
          item.validityStartTime = item.validityTime[0]
          item.validityEndTime = item.validityTime[1]
        }else{
          item.validityStartTime = null
          item.validityEndTime = null
        }

        delete item.validityTime
      })

      data.dataId = data.productId
      data.dataSchool = data.schoolId[0];

      data.bmSchoolOpenExit.bmSchoolOpenExitContentList.forEach((item, index) => {
        item.sort = index;
      });

      console.log(data);
      // return false;

      data.discountIdList = this.discountIdList;
      this.post({
        API: 'update',
        data: data
      }).then(res => {
        this.$message.success('修改成功');
        this.initData();
        this.popupState.showStatus = false;
        this.discountIdList = [];
      }).catch(err => {
        this.$message.error(err);
      })
    },

    // 表格编辑 回显
    tableEdit(rowData, checkStatus) {
      this.showDetailBox = false;
      this.queryAllSchool(this.powerList.add.menuId);
      
      // console.log(rowData.row)
      
      this.detailTableData = [];
      this.productId = rowData.row.productId;
      let discountIdList = []
      console.log('bbbb')
      console.log(rowData.row)
      // 不知是啥，暂时注释
      // rowData.row.bmSchoolOpenList.forEach(item => {
      //   discountIdList.push(item.discountId);
      // })
      let data = {
        id: this.productId,
        schoolId: rowData.row.schoolId,
        // discountId: discountIdList.join(',')
      }
      console.log('aa')
      this.formGet({
        API: 'selectById',
        data: data
      }).then(res => {
        // this.popupState = {
        //   popupName: '编辑校区课程产品',
        //   showStatus: true,
        // }
        if(checkStatus) {
          this.checkStatus = true;
          this.popupState = {
            popupName: '详情',
            showStatus: true,
          }
        }else{
          this.checkStatus = false;
          this.popupState = {
            popupName: '编辑校区课程产品',
            showStatus: true,
          }
        }

        if(res.bmSchoolOpenExit) {
          this.showDetailBox = true;
        }
        this.initDiscountSelect();    // 获取优惠类型 字典
        this.$refs['ruleForm'].resetFields();
        this.formData = res;
        this.formData.schoolId = [];
        this.formData.schoolId.push(rowData.row.schoolId)

        this.formData.bmSchoolOpenList.forEach(item => {
          this.$set(item,'validityTime', [])
          // item.validityTime = [];
          if(item.validityStartTime) {
            item.validityTime.push(item.validityStartTime)
            item.validityTime.push(item.validityEndTime)
          }else{
            item.validityTime = [];
          }

        })

        this.formData.auditionRate = this.formData.bmSchoolOpenList[0].auditionRate
        this.formData.earnestRate = this.formData.bmSchoolOpenList[0].earnestRate
        this.formData.signRate = this.formData.bmSchoolOpenList[0].signRate

        if(!res.bmSchoolOpenExit) {
          this.formData.bmSchoolOpenExit = {
            briefPicture: '',
            descriptionPoster: '',
            bmSchoolOpenExitContentList: [
              {
                isAudition: '0',
                audioOrVideoFile: '',
                durationTime: '',
                fileType: 'video'
              }
            ],
          }
        }

        this.formData.bmSchoolOpenExit.bmSchoolOpenExitContentList.forEach(item => {
          if(item.audioOrVideoFile) {
            item.voiceName = item.audioOrVideoFile
          }
        })

        if(res.bmSchoolOpenExit.briefPicture) {
          let data = {
            ImageId: res.bmSchoolOpenExit.briefPicture
          }
          this.getImgUrlByAliId(data, this.formData.bmSchoolOpenExit, 'briefPictureUrl')
        }
        if(res.bmSchoolOpenExit.descriptionPoster) {
          let data = {
            ImageId: res.bmSchoolOpenExit.descriptionPoster
          }
          this.getImgUrlByAliId(data, this.formData.bmSchoolOpenExit, 'descriptionPosterUrl')
        }


        

        

        let data = {
          courseId: this.formData.courseId
        }
        this.formGet({
          API: 'queryProductByCourseId',
          data: data
        }).then(res => {
          this.productList = res;
        }).catch(err => {
          this.$message.error(err)
        })

        this.changeProduct(this.formData.productId)
        
      }).catch(err => {
        this.$message.error(err);
      })
    },

    tableDetail(rowData, checkStatus) {
      this.tableEdit(rowData, true)
    },



    // 表格删除
    tableDelete(rowData) {
      console.log(rowData.row)
      let productId = rowData.row.productId;
      let schoolOpenExitId  = rowData.row.schoolOpenExitId;

      let discountIdList = [];
      rowData.row.bmSchoolOpenList.forEach(item => {
        console.log(item)
        discountIdList.push(item.discountId)
      })

      let data = {
        id: discountIdList.join(','),
        dataId: discountIdList.join(','),
        dataSchool: rowData.row.schoolId,
        schoolOpenExitId: schoolOpenExitId,
      }

      this.$confirm('是否删除该产品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formGet({
          API: 'deleteById',
          data: data
        }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.initData();
        }).catch(err => {
          this.$message.error(err);
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });

      
      
    },

    initDiscountSelect() {
      this.formGet({
        API: 'queryByDicKey',
        data: {
          dicKey: 'discountType',
        }
      }).then(res => {
        if(this.popupState.popupName == '添加校区课程产品') {
          this.discountSelectList = res;
          this.discountSelectList.forEach((item, index) => {
            if(item.dicLabel == '其它优惠') {
              this.discountSelectList.splice(index, 1);
            }
          })
        }else{
          this.discountSelectList = res;
        }
      }).catch(err => {
        this.$message.error('err');
      })
    },

    showPopup(formName) {
      this.initDiscountSelect();    // 获取优惠类型 字典
      this.checkStatus = false;
      this.queryAllSchool(this.powerList.add.menuId);
      this.showDetailBox = false;
      this.formData.bmSchoolOpenList = [
        {
          discountType: '',
          remarkDiscount: '',
          discountPrice: '',
          validityTime: [],
          discountMethod: '',
          productId: '',
          subjectDiscount: '',
        }
      ]
      this.formData.bmSchoolOpenExit = {
        briefPicture: '',
        descriptionPoster: '',
        bmSchoolOpenExitContentList: [
          {
            isAudition: '0',
            audioOrVideoFile: '',
            durationTime: '',
            fileType: 'video'
          }
        ],
      },
      this.formData.auditionRate = '';
      this.formData.earnestRate = '';
      this.formData.signRate = '';
      this.$refs[formName].resetFields();   // 初始化
      this.detailTableData = [];
      this.popupState = {
        showStatus: true,
        popupName: '添加校区课程产品',
      }

    },
    searchData(searchValue) {
      this.page.curPage = 1;
      this.initData(searchValue)
    },

    changeSchool(e) {
      this.searchForm.schoolIdArr = []
      if(e == '') {
        // this.searchForm.schoolIdArr = this.jwtAuth.schoolId.split(',')
        this.schoolList.forEach(item => {
          this.searchForm.schoolIdArr.push(item.schoolId);
        })
      }else{
        this.searchForm.schoolIdArr.push(e);
      }
    },

    changeType(e, index) {
      let discountList = this.formData.bmSchoolOpenList
      for(let i=0; i<discountList.length; i++) {
        if(discountList[i].discountType == 2) {   // 团报优惠
          if(discountList[i].discountMethod == 1) {
            this.$message.error('团报优惠优惠金额不可为百分比！');
            this.formData.bmSchoolOpenList[i].discountMethod = '2';
            break;
          }
        }
      }
    },

    
    changeCourse(e) {
      this.formData.productId = ''
      this.detailTableData = [];
      let data = {
        courseId: e
      }
      this.formGet({
        API: 'queryProductByCourseId',
        data: data
      }).then(res => {
        this.productList = res;
      }).catch(err => {
        this.$message.error(err)
      })
    }, 

    // 删除优惠
    deleteDiscount(index) {
      if(this.checkStatus) {
        return false;
      }
      let arr = this.formData.bmSchoolOpenList;

      if(arr.length == 1) {
        this.$message.error('仅剩一项无法进行删除操作')
      }else{
        if(arr[index].discountId) {
          this.discountIdList.push(arr[index].discountId);
        }
        console.log(this.discountIdList)
        arr.splice(index, 1);
      }
    },
    // 添加优惠
    addDiscount(index) {
      if(this.checkStatus) {
        return false;
      }
      let obj = {
        subjectDiscount: '',
        remarkDiscount: '',
        discountPrice: '',
        discountMethod: '',
        discountType: '',
        validityTime: [],
        productId: '',
      }

      let arr = this.formData.bmSchoolOpenList;
      arr.splice(index + 1, 0, obj);;
    },


    // 删除目录
    deleteCatalog(index) {
      if(this.checkStatus) {
        return false;
      }
      let arr = this.formData.bmSchoolOpenExit.bmSchoolOpenExitContentList;

      if(arr.length == 1) {
        this.$message.error('仅剩一项无法进行删除操作')
      }else{
        // if(arr[index].discountId) {
        //   this.discountIdList.push(arr[index].discountId);
        // }
        // console.log(this.discountIdList)
        arr.splice(index, 1);
      }
    },
    // 添加目录
    addCatalog(index) {
      if(this.checkStatus) {
        return false;
      }
      let obj = {
        isAudition: '0',
        audioOrVideoFile: '',
        durationTime: '',
        fileType: 'video'
      }

      let arr = this.formData.bmSchoolOpenExit.bmSchoolOpenExitContentList;
      arr.push(obj)
      // arr.splice(index + 1, 0, obj);
    },

    changeProduct(e) {
      let data = {
        id: e,
        schoolId: this.jwtAuth.schoolId
      }
      this.formGet({
        API: 'productSelectById',
        data: data
      }).then(res => {
        let subjectNameList = [];
        let subjectHourList = []
        res.productSubjectList.forEach(item => {
          subjectNameList.push(item.subjectName)
          subjectHourList.push(item.classHour)
        })

        res.subjectName = subjectNameList.join('</br>');
        res.subjectHour = subjectHourList.join('</br>');
        // console.log(res)
        this.detailTableData = []
        this.productPrice = Number(res.productPrice);
        this.mealsPrice = Number(res.mealsPrice)
        this.incidentalPrice = Number(res.incidentalPrice)
        this.otherPrice = Number(res.otherPrice)
        this.detailTableData.push(res);
      }).catch(err => {
        this.$message.error(err);
      })
    },

    

    valiSubjectDiscount(item, index) {
      if(item.subjectDiscount == '') {
        return false;
      }
      let percent

      if(typeof item.subjectDiscount != 'number') {
        this.$message.error('折扣优惠必须为数字')
        item.subjectDiscount = ''
        return false
      }else{
        percent = Number(item.subjectDiscount)
      }

      if(percent < 0 || percent > 100) {
        this.$message.error('折扣优惠必须在1-100之间')
        item.subjectDiscount = '';
      }
    },

    valiDiscountPrice(item, index) {
      if(item.discountPrice == '') {
        return false;
      }
      let price;
      if(typeof item.discountPrice != 'number') {
        this.$message.error('优惠金额必须为数字')
        item.discountPrice = ''
        return false
      }else{
        price = Number(item.discountPrice)
      }

      if(price > this.productPrice) {
        this.$message.error('优惠金额必须小于课程指导价格')
        item.discountPrice = '';
      }
    },

    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.page.pageSize = val;
      this.initData();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page.curPage = val;
      this.initData();
    }
    
  },
  computed: {
    ...mapState([
    ]),
    // ...mapGetters(["selectedIds"])
  },
  components: {
    adminTable,
    uploadAliyun,
  },
}

</script>